<?php

namespace Beerus\Modules\BrandRights\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel;
use Biz\model\brandRights\BrandLevelRightsSource;
use Biz\model\brandRights\BrandRightsSource;
use Biz\service\BrandRights\BrandRightsSourceService;
use Biz\tools\helper\Common;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Displayers\Actions;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\Support\MessageBag;

class LevelRightsController extends Controller
{
    public const  PAGE_SIZE = 20;

    /**
     * 获取列表
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function index(Request $request, Content $content): Content
    {
        $params = $request->all();
        [$where, $sWhere] = $this->_getWhere($params);
        $levelSourceRights = [];
        $levelRights = BrandLevelRightsSource::dataSelect($where);
        $levelRightsIds = empty($levelRights) ? [] : array_column($levelRights, 'source_rights_id');
        if (!empty($levelRightsIds)) {
            $sWhere['id'] = $levelRightsIds;
            $sourceRights = BrandRightsSourceService::getAllSource('*', $sWhere);
            $sourceRights = array_column($sourceRights, null, 'id');
            foreach ($levelRights as $key => $item) {
                if (!isset($sourceRights[$item['source_rights_id']])) {
                    continue;
                }
                $rights = $sourceRights[$item['source_rights_id']];
                $levelSourceRights[$key] = $item;
                $levelSourceRights[$key]['rights_name'] = $rights['rights_name'];
                $levelSourceRights[$key]['rights_type'] = $rights['rights_type'];
            }
        }
        $gridModel = new GridDataModel($levelSourceRights);
        $grid = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->filter(function ($filter) {
                    $filter->disableIdFilter();
                    // 在这里添加字段过滤器
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('source_rights_id', '权益ID')->placeholder('权益ID');
                        $filter->equal('rights_name', '权益英文标识')->placeholder('权益英文标识');
                    });
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('rights_type', '权益类型')->select(BrandRightsSource::RIGHTS_TYPE_ARR);
                        $filter->equal('data_status', '状态')->select(BrandRightsSource::STATUS_ARR);
                    });
                    $filter->expand();//默认展开
                });
                $grid->disablePagination();
                $grid->disableCreateButton();
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->column('id', '序号')->width(60);
                $grid->column('source_rights_id', '权益ID')->width(60);
                $grid->column('rights_title', '权益名称')->width(100);
                $grid->column('rights_name', '权益英文名称')->copyable()->width(220);
                $grid->column('rights_type', '权益类型')->using(
                    BrandRightsSource::RIGHTS_TYPE_ARR
                    , '未知')->label([
                    BrandRightsSource::RIGHTS_TYPE_OPEN => 'warning',
                    BrandRightsSource::RIGHTS_TYPE_LIMIT_NUM => 'info',
                    BrandRightsSource::RIGHTS_TYPE_NUM => 'success',
                    BrandRightsSource::RIGHTS_TYPE_OTHER => 'default',
                ])->width(80);

                $grid->column('rights_desc', '权益说明')->width(240);

                $grid->column('rights_use_pic', '使用说明')->display(function ($rights_use_pic) {
                    if (!empty($rights_use_pic)) {
                        $img = ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $rights_use_pic, ImgUrl::IMAGE_SIZE_ORI_NPHONE);
                        return "<a href='$img' target='_blank' alt='{$this->rights_name}'>查看</a>";
                    }
                    return ' - ';
                })->width(80);

                $grid->column('sort_weight', '排序')->editable()->width(60);

                $grid->column('data_status', '状态')->using(
                    BrandRightsSource::STATUS_ARR
                    , '未知')->label([
                    BrandRightsSource::STATUS_NORMAL => 'success',
                    BrandRightsSource::STATUS_DELETE => 'danger',
                ])->width(80);

                $grid->setActionClass(Actions::class);
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                    $actions->disableView();
                });
            }
        );
        $content->row($grid);

        return $content
            ->header('等级基础权益管理列表')
            ->description(' ')
            ->breadcrumb(['text' => '等级基础权益管理列表', 'url' => '/BrandRights/levelrights']);
    }


    /**
     * 获取查询条件
     * @param $params
     * @return array
     */
    private function _getWhere($params): array
    {
        $where = $sWhere = [];
        $type = $params['rights_type'];
        $rights_id = $params['id'] ?? '';
        $rights_name = $params['rights_name'] ?? '';
        $status = isset($params['data_status']) && $params['data_status'] != '' ? $params['data_status'] : null;
        if ($type) {
            $sWhere['rights_type'] = $type;
        }
        if ($rights_id) {
            $where['source_rights_id'] = $rights_id;
        }
        if ($rights_name) {
            $sWhere['rights_name[~]'] = $rights_name . '%';
        }
        if (!is_null($status)) {
            $where['data_status'] = $status;
        }

        $where['ORDER'] = [
            'sort_weight' => 'ASC'
        ];

        return [$where, $sWhere];
    }


    /**
     * 编辑
     * @param $id
     * @param Content $content
     * @return Content|RedirectResponse
     */
    public function edit($id, Content $content)
    {
        if (!$id) {
            admin_error('参数错误！', 'warning');
        }
        $where['id'] = $id;
        //编辑
        $baseInfo = BrandLevelRightsSource::dataSelectInfo($where);
        if (!$baseInfo) {
            $error = new MessageBag([
                'title' => '信息不存在或已删除',
            ]);
            return back()->with(compact('error'));
        }
        $baseForm = new Form($baseInfo);
        $baseForm->disableReset();
        $baseForm->text('rights_title', '权益名称');
        $baseForm->text('rights_desc', '权益描述');
        $baseForm->imgUpload('rights_use_pic', '权益使用说明图片', false, [
            'isUpload' => true,
            'isGetUrl' => true,
            'imgType' => ImgUrl::APPTYPE_BIZ,
            'imgSize' => ImgUrl::IMAGE_SIZE_ORI_NPHONE
        ]);
        $baseForm->hidden('id');
        $baseForm->confirm('确定更新吗？');
        $baseForm->action('/admin/BrandRights/levelrights/save');

        return $content
            ->header('修改')
            ->description(' ')
            ->breadcrumb(
                ['text' => '等级基础权益管理列表', 'url' => '/BrandRights/levelrights'],
                ['text' => '等级基础权益修改']
            )
            ->row($baseForm);

    }

    /**
     * 保存
     * @param Request $request
     * @return Application|RedirectResponse|Redirector
     */
    public function save(Request $request)
    {
        try {
            $params = $request->all();
            $rules = [
                "rights_title" => 'required',
            ];
            //更新
            $info = BrandLevelRightsSource::dataSelectInfo(['id' => $params['id']], ['id']);
            if (!$info) {
                throw new \Exception('该权益不存在！');
            }
            //校验参数
            $res_msg = Common::validatorRule($rules, $params);
            if ($res_msg !== true) {
                throw new \Exception($res_msg);
            }
            $data = [
                "rights_desc" => $params["rights_desc"] ?? '',
                "rights_title" => $params["rights_title"] ?? '',
                "rights_use_pic" => $params["rights_use_pic"] ?? '',
            ];
            $success = new MessageBag([
                'title' => '成功',
            ]);
            //更新
            BrandLevelRightsSource::dataUpdate($data, ['id' => $params['id']]);

        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage(),
            ]);
            return back()->with(compact('error'))->withInput();
        }
        return redirect('/admin/BrandRights/levelrights')->with(compact('success'));
    }


    /**
     * 更改权益排序
     * @param Request $request
     * @return JsonResponse
     */
    public function sortWeight(Request $request,$id): JsonResponse
    {
        try {
            $params = $request->all();

            $rule = [
                'name'=>'required|string',
                'value' => 'required|int',
                'pk' => 'required|int',
            ];
            $validator_msg = Common::validatorRule($rule, $params);
            if ($validator_msg !== true) {
                throw  new \Exception($validator_msg);
            }
            if($params['name'] != 'sort_weight'){
                throw  new \Exception('异常操作');
            }
            $data['sort_weight'] = $params['value'];
            $info = BrandLevelRightsSource::dataSelectInfo(['id' => $params['pk']]);
            if (empty($info)) {
                throw new \Exception('不存在的权益');
            }
            BrandLevelRightsSource::dataUpdate($data,['id'=>$params['pk']]);
            $success = [
                'message' => '操作成功',
                'status' => true,
            ];
        } catch (\Exception $e) {
            $success = [
                'message' => '操作失败,' . $e->getMessage(),
                'status' => false,
            ];
        }

        return response()->json($success);

    }


}